package com.um.jdy.platform.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.um.jdy.common.platform.entity.po.CompanyMenu;
import com.um.jdy.common.platform.service.CompanyMenuService;
import com.um.jdy.platform.system.service.PermissionService;
import com.um.jdy.common.system.entity.po.Menu;
import com.um.jdy.common.system.service.MenuService;
import com.um.springboot.starter.service.ApiPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 甘天伟
 * @date 2025/3/8
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    ApiPermissionService apiPermissionService;

    /**
     * 加载权限列表
     *
     * @param userId   用户ID
     * @param menuList 菜单列表
     */
    @Override
    public void loadPermissionList(String userId, List<CompanyMenu> menuList) {
        if (StrUtil.isBlank(userId) || CollUtil.isEmpty(menuList)) {
            return;
        }

        ArrayList<String> permList = new ArrayList<>();
        for (CompanyMenu menu : menuList) {
            String apiPermission = menu.getApiPermission();
            if (StrUtil.isBlank(apiPermission) || "[]".equals(apiPermission)) {
                continue;
            }
            try {
                permList.addAll(JSONUtil.parseArray(apiPermission).toList(String.class));
            } catch (Exception ex) {
                log.warn("菜单权限配置异常：{}", menu);
            }
        }

        if (CollUtil.isNotEmpty(permList)) {
            apiPermissionService.loadPermissionList(userId, permList);
        }
    }

}
